import io from 'socket.io-client'
import Vue from 'vue'
class Node {
  constructor (options = {}) {
    this.loginobj = {
      mid: '',
      emid: '',
      coid: '',
      group: '',
      username: ''
    }
    this.options = {
      nodejsServer: '',
      group: '',
      mName: ''
    }
    this.options = {...this.options, ...options}
    this.nodeMidAbstract()
  }
  setOption (options) {
    this.options = {...this.options, ...options}
    this.nodeMidAbstract()
  }
  nodeMidAbstract () {
    const data = {
      'group': this.options.group
    }
    Vue.prototype.$axios({
      method: 'post',
      url: `${Vue.prototype.$site.homeServer}/front/nodetalk/nodeMidAbstract.htm`,
      data: Vue.prototype.$qs.stringify(data)
    }).then(res => {
      if (res.data.errorMsg) {
        Vue.prototype.$message.error(res.data.errorMsg)
      } else {
        this.loginobj.mid = res.data.userid
        this.loginobj.emid = res.data.emid
        this.loginobj.coid = res.data.coid
        this.loginobj.group = this.options.group
        this.loginobj.username = this.options.mName
        this.options.nodejsServer = res.data.nodejsServer
        this.initSuccess()
      }
    })
  }
  initSuccess () {
    if (!window.socket) {
      window.socket = io(`${this.options.nodejsServer}/chat`)
    }
    setTimeout(() => {
      window.socket.emit('login', this.loginobj)
      if (!window.socket.hasListeners('message')) {
        window.socket.on('message', (obj) => {
          this.nodeMessage(obj)
        })
      }
    }, 1000)
  }
  emit () {
    window.socket.emit('login', this.loginobj)
  }
  logout () {
    let obj = {
      mid: this.loginobj.mid,
      group: this.options.group
    }
    if (window.socket) {
      window.socket.emit('logout', JSON.stringify(obj))
    }
  }
  nodeMessage (obj) {
    obj.itype = Number.parseInt(obj.itype)
    if (obj) {
      switch (obj.itype) {
        case 7000:
          Vue.prototype.$store.commit('setAIVideoNode', obj.payload)
          break
        case 7001:
          Vue.prototype.$store.commit('setProjectNode', obj.payload)
          break
        case 7002:
          Vue.prototype.$store.commit('setVideoListNode', obj.payload)
          break
        case 7100:
          Vue.prototype.$store.commit('setProjectBroadcastNode', obj.payload)
          break
        case 7111:
        case 7112:
        case 7113:
        case 7114:
        case 7115:
        case 7116:
          Vue.prototype.$store.commit('setCompanyBroadcastNode', {...obj.payload, ...{'itype': obj.itype}})
          break
        default:
          break
      }
    }
  }
}

export default Node
